# Create your views here.
import base64
import struct
import string
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
import datetime
def main(request):
    #values = request.META.items()
    #values.sort()
    #html = []
    #for k, v in values:
        #html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    #return HttpResponse('<table>%s</table>' % '\n'.join(html))
    #print request.META['HTTP_REFERER']
    #print request.META['REMOTE_ADDR']

    content =datetime.datetime.now() 
    #return render_to_response('index.html', 'content': now})
    response = render_to_response('index.html', locals())
    #response.set_cookie('favorite_color','red')
    #print 'favorite color is %s' % request.COOKIES['favorite_color'] 
    #request.session['favorite_color'] = 'blue'
    print request.session['favorite_color']
    return response
    #return HttpResponse("hello world")

def ult_login(request):
    username = request.session['login']
    print request.user
    
    return render_to_response('login.html',locals())



def auth(request):
    username, response = ntlm_auth(request)
    if response:
        return response

def get_msg_str(msg,start):
    msg_len, _, msg_off = struct.unpack("<HHH", msg[start:start + 6])
    return msg[msg_off:msg_off + msg_len].replace("\0", '')
def ntlm_auth(request):
    username = None
    response = None
    auth = request.META.get('HTTP_AUTHORIZATION')
    if not auth:
        response = HttpResponse(status=401)
        response['WWW-Authenticate'] = "NTLM"
        return username, response
    elif auth[:4] == "NTLM":
        msg = base64.b64decode(auth[4:])
        ntlm_fmt = "<8sb" #string, length 8, 4 - op
        NLTM_SIG = "NTLMSSP\0"
        signature, op = struct.unpack(ntlm_fmt, msg[:9])
        if signature != NLTM_SIG:
            print "error header not recognized"
        else:
            print "recognized"
            if op == 1:
                out_msg2 = "NTLMSSP\x00\x02\x00\x00\x00" + \
		           "\x00\x00\x00\x00" + \
			   "\x00\x00\x00\x00" + \
			   "\x01\x02\x81\x00" + \
			   "\x00\x00\x00\x00\x00\x00\x00\x00" + \
			   "\x00\x00\x00\x00\x00\x00\x00\x00" + \
			   "\x00\x00\x00\x00\x00\x00\x00\x00" 
	        response = HttpResponse(status=401)
                response['WWW-Authenticate'] = "NTLM " + base64.b64encode(out_msg2).strip()
            elif op == 3:
                username = get_msg_str(msg, 36)
		request.session['login'] = username
	        response = HttpResponseRedirect('/login')
    return username, response
